import {getGoodDetail, goodsQuery} from "@mall/api/good";
import {addGoodsToCart} from "@mall/api/shopCart";
import router from "@src/router";

Component({
  properties: {},
  data: {
    storeId: null,
    deliveryTyp: '',
    keyword: '',
    hiddenToast: true,
    selectSkuObj: null,
    goodsObj: null,
  },
  methods: {
    onLoad(options) {
      let {storeId, deliveryTyp} = options
      this.setData({storeId, deliveryTyp});
    },
    inputFocus(e) {
      let keyword = e.detail;
      this.fetchGoods(keyword);
    },
    fetchGoods(keyword) {
      if (!keyword.trim()) {
        this.setData({goodsList: []})
        return;
      }
      let params = {
        keyword: keyword,
        storeId: this.data.storeId,
        pageNum: 1,
        pageSize: 30
      }
      goodsQuery(params).then(res => {
        this.setData({goodsList: res.data.list})
      })
    },
    handleBack() {
      router.back()
    },
    handleAdd(e) {
      let goods = e.detail;
      if (goods.skuInfo.skuList.length === 1) {
        let sku = goods.skuInfo.skuList[0];
        let params = {
          storeId: this.data.storeId,
          goodsId: goods.goodId,
          num: 1,
          skuId: sku.skuId,
          type: this.data.deliveryType,
          cartType: 0,
        };
        this.addCart(params);
      } else {
        // 获取商品详情
        let params = {
          goodsSerial: goods.goodsSerial,
          storeId: this.data.storeId
        }
        wx.showLoading({title: "加载中", mask: true});
        getGoodDetail(params).then(res => {
          wx.hideLoading();
          this.setData({goodsObj: res.data})
          setTimeout(res => {
            this.setData({showSkuDialog: true})
          }, 300)
        }).catch(error => {
          wx.hideLoading();
        })
      }
    },
    addCart(params) {
      params.type = 'LOCAL';
      // 直接添加到购物车
      wx.showLoading({title: "添加中...", mask: true});
      addGoodsToCart(params).then(res => {
        wx.hideLoading();
        this.setData({hiddenToast: false})
        setTimeout(() => {
          this.setData({hiddenToast: true})
        }, 2000)
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('refresh');
      }).catch(() => {
        wx.hideLoading();
      })
    },
    skuObjFun(detail) {
      this.setData({
        selectSkuObj: detail.detail
      })
    },
    specAddCart(e) {
      let num = 1;
      if (e.detail) {
        num = e.detail
      }
      let sku = this.data.selectSkuObj;
      let params = {
        storeId: this.data.storeId,
        goodsId: this.data.goodsObj.goodsId,
        num: num,
        skuId: sku.skuId,
        type: this.data.deliveryType,
        cartType: 0,
      };
      this.addCart(params);
    },
  }
});
